package com.groupten.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.groupten.Dao.ConfigureRuleDao;
import com.groupten.Entity.ConfigureRuleEntity;
import com.groupten.Service.ConfigureRuleService;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("configureRuleService")
public class ConfigureRuleServiceImpl extends ServiceImpl<ConfigureRuleDao, ConfigureRuleEntity> implements ConfigureRuleService {

    @Autowired
    private ConfigureRuleDao configureRuleDao;

    @Override
    public ConfigureRuleEntity selectById(Long id) {
        return configureRuleDao.selectById(id);
    }

    @Override
    public ConfigureRuleEntity selectByName(String name) {
        LambdaQueryWrapper<ConfigureRuleEntity> queryWrapper = new LambdaQueryWrapper<ConfigureRuleEntity>()
                .eq(ConfigureRuleEntity::getRuleName, name);
        return configureRuleDao.selectOne(queryWrapper);
    }

    @Override
    public String updateByName(String name, Map<String, String> newData) {
        if (selectByName(name)==null){
            // 规则不存在
            return "The rule does not exist";
        }
        ConfigureRuleEntity configureRuleEntity = selectByName(name);
        for (Map.Entry<String, String> entry : newData.entrySet()) {
            switch (entry.getKey()){
                case "singlechoiceNumber":
                    configureRuleEntity.setSinglechoiceNumber(Integer.parseInt(entry.getValue()));
                    break;
                case "multiplechoiceNumber":
                    configureRuleEntity.setMultiplechoiceNumber(Integer.parseInt(entry.getValue()));
                    break;
                case "blankNumber":
                    configureRuleEntity.setBlankNumber(Integer.parseInt(entry.getValue()));
                    break;
                case "passingRate":
                    configureRuleEntity.setPassingRate(Double.parseDouble(entry.getValue()));
                    break;
                case "ruleName":
                    configureRuleEntity.setRuleName(entry.getValue());
                    break;
                default:
                    break;
            }
        }
        return configureRuleDao.updateById(configureRuleEntity) == 1? "success" : "fail";
    }

    @Override
    public String insert(ConfigureRuleEntity configureRuleEntity) {
        if (selectByName(configureRuleEntity.getRuleName())!=null){
            // 该规则名称已被占用或该规则已存在
            return "The rule already exists";
        }else return configureRuleDao.insert(configureRuleEntity)>0? "success" : "fail";
    }

    @Override
    public Boolean deleteById(Long id) {
        return configureRuleDao.deleteById(id)>0;
    }


}

